<template>
	<view class="page">
		<!-- 电站信息 -->
		<view class="station-info">
			<view class="charger-list">
				<terminal-item :info="terminalInfo" v-if="terminalInfo"></terminal-item>
			</view>
		</view>
		 
		<!-- 价格信息 -->
		<view class="price-info">
			<view class="title flex">
				<text>价格信息</text>
				<view class="more flex" @click="showPricePopup">
					<text>全部时段</text>
					<u-icon name="arrow-right" size="22rpx" color="#777" :bold="true"></u-icon>
				</view>
			</view>
			<view class="price-list">
				<price-card
					v-for="(item, index) in displayPriceList"
					:key="index"
					:price="item"
					:displayTime="item.displayTime"
					:isCurrent="index === 0"
				></price-card>
				<view class="empty flex" style="justify-content: center;width: 100%;">
					<u-empty iconSize="50" v-if="displayPriceList.length == 0"></u-empty>
				</view>
			</view>
		</view>

		<!-- 充电信息 -->
		<view class="charge-info">
			<view class="flex flex-between">
				<view class="charge-title">充电信息</view>
				<text class="status" v-if="!vehicleItem">未设置</text>
			</view>
			<view class="add-plate flex flex-between" @click="toCarPage">
				<view v-if="vehicleItem" style="letter-spacing: 4rpx;">{{ vehicleItem.plateNumber || '&nbsp;' }}</view>
				<view v-else>&nbsp;</view>
				<view><button class="add-btn">{{ vehicleItem ? '更换' : '添加' }}车辆</button></view>
			</view>
		</view>

		<!-- 充电时长 -->
		<view class="duration-section">
			<view class="charge-title">充电时长</view>
			<view class="duration-options">
				<view class="duration-grid">
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 10 }"
						@click="selectDuration(10)"
					>10分钟</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 60 }"
						@click="selectDuration(60)"
					>1小时</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 120 }"
						@click="selectDuration(120)"
					>2小时</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 180 }"
						@click="selectDuration(180)"
					>3小时</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 240 }"
						@click="selectDuration(240)"
					>4小时</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === 300 }"
						@click="selectDuration(300)"
					>5小时</view>
					<view 
						class="duration-item" 
						:class="{ active: formData.chargingDuration === '' }"
						@click="selectDuration('')"
					>充满自停</view>
				</view>
			</view>
		</view>
		
		<!-- +++ 新增优惠券选择区域 +++ -->
		  <view class="coupon-section" @click="showCouponSelector">
		    <view class="charge-title">优惠券</view>
		    <view class="coupon-select flex flex-between">
		      <text class="coupon-text" v-if="selectedCoupon">
		        {{ selectedCoupon.name }}
		      </text>
		      <text class="coupon-text" v-else>选择优惠券</text>
		      <u-icon name="arrow-right" size="24rpx" color="#777"></u-icon>
		    </view>
		  </view>
		  <!-- +++ 结束新增 +++ -->
		
		<!-- 开始充电按钮 -->
		<view 
			class="start-charge-btn" 
			:class="{ disabled: !isFormValid || !totalPrice }"
			@click="isFormValid && preSubmit()"
			v-if="!isFleetUser"
		>
			开始充电 ({{ totalPrice || 0 }}/度)
		</view>
		
		<!-- 价格详情弹窗 -->
		<price-popup
			:show="pricePopupVisible"
			:priceList="allPriceList"
			:currentTimeSegmentIndex="currentTimeSegmentIndex"
			@close="closePricePopup"
		></price-popup>
		
		<!-- +++ 新增优惠券选择器 +++ -->
		  <coupon-selector 
		    ref="couponSelector"
		    :orderAmount="estimatedAmount"
		    :coupons="availableCoupons"
		    @select="onCouponSelect"
		  />
	</view>
</template>

<script>
import priceMixin from '@/mixins/priceMixin'
import ChargerItem from '@/components/charger/ChargerItem'
import PriceCard from '@/components/price/PriceCard'
import PricePopup from '@/components/price/PricePopup'
import CouponSelector from '@/components/coupon-selector'
import { getIsFleetUser } from '@/common/cacheManager.js';


export default {
	components: {
		ChargerItem,
		PriceCard,
		PricePopup,
		CouponSelector
	},
	
	mixins: [priceMixin],
	
	data() {
		return {
			terminalInfo: null,
			stationId: 0,  // 电站ID
			terminalId: 0, // 电站终端ID
			speedText: ['慢', '快', '超'],
			speedClass: ['slow', 'fast', 'super'],
			tenantId: 0,  //服务商
			currentPrice: 0, // 当前时段的价格
			totalPrice: 0, // 当前时段总价格
			stationPriceList: [], // 价格列表
			displayPriceList: [], // 用于显示的价格列表（当前和下一个时段）
			allPriceList: [], // 用于显示全部时段的价格列表
			// +++ 新增优惠券相关数据 +++
			selectedCoupon: null,           // 选中的优惠券
			availableCoupons: [],           // 可用优惠券列表
			estimatedAmount: 0,             // 预估金额（用于优惠券筛选）
			
			pricePopupVisible: false,
			wallet: null,
			tenant: null, //租户			
			paymentList: [
				{ label: '钱包', value: 'wallet', amount: 0, icon: 'rmb-circle', color: '#f40', size: 20 },
				{ label: '微信支付', value: 'wxpay', amount: 0, icon: 'weixin-fill', color: '#07c160', size: 26 },
				{ label: '支付宝支付', value: 'alipay', amount: 0, icon: 'zhifubao', color: '#1677ff', size: 26 },
			],
			payway: 'wxpay',
			
			vehicleItem: null,
			lock: false,

			formData: {
				stationId: null, //电站ID
				terminalId: null, // 终端id
				gunCode: "01",    // 枪码
				chargingDuration: "", // 默认选中1小时
				vehicleId: 0 ,// 车辆id
				plateNumber: '', // 车牌号
			},
			isFleetUser: false,
		}
	},
	onLoad({ id, terminalId }) {
		this.stationId = id;
		this.terminalId = terminalId;
		this.initTerminalInfo();
		this.fetchIsFleetUserStatus();
		// 监听车牌信息变更事件
		uni.$on('updateCarInfoEvent', carInfo => {
			if (Array.isArray(carInfo.plateNumber)) {
				carInfo.plateNumber = carInfo.plateNumber.join('')
			}
			this.vehicleItem = carInfo;
			this.formData.plateNumber = this.vehicleItem.plateNumber;
			this.formData.vehicleId = this.vehicleItem.id;
		})
	},
	methods: {
		// 新增一个方法来获取并设置 isFleetUser 状态
		async fetchIsFleetUserStatus() {
		    try {
		        const status = await getIsFleetUser(); // 调用缓存管理器中的函数
		        this.isFleetUser = status; // 将结果存入 data
		    } catch (error) {
		         // 处理错误，例如网络问题或 API 错误
		         console.error('获取 isFleetUser 状态失败:', error);
		         // 可以选择性地设置一个默认值，或者显示错误提示
		         // 为了安全起见，如果获取失败，可以默认隐藏（即设为 true），或者显示（设为 false）
		         // 这里我们假设获取失败时默认显示冻结金额（更保守）
		         this.isFleetUser = false;
		         // 或者显示用户友好的提示
		         // uni.showToast({ title: '获取用户状态失败', icon: 'none' });
		    }
		},
		initTerminalInfo() {
			this.$http_api.chargingStationInfo({ id: this.terminalId }).then(res => {
				this.terminalInfo = res;
				this.formData.stationId = res.stationId;
				this.formData.gunCode = res.gunCode;
				this.formData.terminalId = res.terminalId;
				this.tenantId = res.tenantId; 
				this.getSystemTenant();
				this.getVehicleList();
				this.getUserWallet();
				this.getStationPrice();
			})
		},
		
		// +++ 新增方法：显示优惠券选择器 +++
		    showCouponSelector() {
		      // 计算预估金额（根据当前价格和充电时长）
		      this.calculateEstimatedAmount();
		      
		      // 获取可用优惠券
		      this.getAvailableCoupons().then(() => {
		        this.$refs.couponSelector.show();
		      });
		    },
			
		// +++ 新增方法：获取可用优惠券 +++
		    async getAvailableCoupons() {
		      try {
		        const res = await this.$http_api.couponList({ 
		          status: 1, // 可用状态
		          pageNo: 1,
		          pageSize: 100
		        });
		        
		        // 筛选当前订单可用的优惠券
		        this.availableCoupons = (res.list || []).filter(coupon => {
		          return parseFloat(this.estimatedAmount) >= parseFloat(coupon.usePrice);
		        });
		      } catch (error) {
		        console.error('获取优惠券失败', error);
		        this.availableCoupons = [];
		      }
		    },
			
			// +++ 新增方法：计算预估金额 +++
			    calculateEstimatedAmount() {
			      this.estimatedAmount = 10000;
			    },
		    
		    // +++ 新增方法：处理优惠券选择 +++
		    onCouponSelect(coupon) {
		      this.selectedCoupon = coupon
		    },
		
		// 切换支付方式
		selectPayment(payway) {
			if (payway == 'wallet' && this.wallet.totalAmount <= 0) {
				return;
			}
			this.payway = payway;
		},
		
		// 获取用户默认车牌号
		getVehicleList() {
			this.$http_api.userVehicleList({}).then((res) => {
				if (res && res.length > 0) {
					const defaultCar = res.find(item => item.defaultSelected == 1)
					if (!defaultCar) return;
					this.vehicleItem = defaultCar;
					this.formData.vehicleId = this.vehicleItem.id;
					this.formData.plateNumber = this.vehicleItem.plateNumber;
				}
			})
		},
		
		toCarPage() {
			uni.navigateTo({ url: '/pages/user/users/car/index?type=order' });
		},
		getSystemTenant() {
			this.$http_api.tenantDetail({id:this.tenantId}).then((res)=>{
				this.tenant = res
			})
		},
		
		
		getUserWallet() {
			this.$http_api.userWallet({}).then((res)=>{
				this.wallet = res
			})
		},
		
		// 获取价格时间段
		getStationPrice() {
			this.$http_api.stationPrice({ id: this.stationId }).then((res) => {
				this.stationPriceList = res.timeSegments;
				this.currentPrice = res.currentPrice
				this.totalPrice = res.totalPrice
				
				// 处理全部时段的显示
				this.allPriceList = this.stationPriceList.map(segment => ({
					...segment,
					displayTime: this.formatTimeRange(segment.startTime, segment.endTime)
				}));
				
				// 处理当前和下一个时段的显示
				this.displayPriceList = [];
				
				const currentSegment = this.getCurrentTimeSegment();
				if(currentSegment) {
					this.displayPriceList.push({
						...currentSegment,
						displayTime: '当前时段'
					});
				}
			})
		},
		
		showPricePopup() {
			this.pricePopupVisible = true
		},
		closePricePopup() {
			this.pricePopupVisible = false
		},
		
		// 添加选择充电时长的方法
		selectDuration(duration) { 
			this.formData.chargingDuration = duration;
		},
		
		//跳转充值 
		recharge() {
			// 充值逻辑
			uni.navigateTo({
				url: '/pages/user/wallet/recharge'
			})
		},
		preSubmit() { 
			 if (this.lock) return;
			 
			 let balanceLimit = this.tenant.balanceLimit || 0
			 let balance = this.wallet.balance || 0;
			 
			 if (balance <= 0) {
			 	return uni.$u.toast('账户余额不能为0');
			 } 
			
			if (!this.currentPrice || this.currentPrice <= 0) {
				return uni.$u.toast('当前价格获取失败');
			}
			if (!this.wallet || this.wallet.balance <= 0) {
				return uni.$u.toast('账户余额不能为0');
			} 
			
			// 表单验证
			if (!this.formData.stationId) {
				return uni.$u.toast('电站ID不能为空');
			}
			if (!this.formData.terminalId) {
				return uni.$u.toast('终端ID不能为空');
			}
			if (!this.formData.vehicleId) {
				return uni.$u.toast('请选择车辆');
			}
			
			if (!this.formData.gunCode) {
				return uni.$u.toast('枪号不能为空');
			}
			 
			 if(balanceLimit >= balance){				 
				uni.showModal({
					title:'充电确认',
					content: '当前账户余额不足,为了不影响体验，请确认',
					confirmText: "继续",
					cancelText: '充值',
					success: (res) => {
						if (res.confirm) {
							//继续充电
						    this.submit();
						} else {
							//跳转到充值页面 
							this.recharge();
						}
					}
				}) 
			 }else{
				 this.submit();
			 }
		},
		submit() { 
			if (this.lock) return;
			
			if (!this.currentPrice || this.currentPrice <= 0) {
				return uni.$u.toast('当前价格获取失败');
			}
			if (!this.wallet || this.wallet.balance <= 0) {
				return uni.$u.toast('账户余额不能为0');
			} 
			
			// 表单验证
			if (!this.formData.terminalId) {
				return uni.$u.toast('终端ID不能为空');
			}
			if (!this.formData.vehicleId) {
				return uni.$u.toast('请选择车辆');
			}
			
			if (!this.formData.gunCode) {
				return uni.$u.toast('枪号不能为空');
			}
			
			const data = {
			     ...this.formData,
				 couponId: this.selectedCoupon?.id ? [this.selectedCoupon?.id] : []
			   }
		 
			this.$http_api.createOrder(data).then(res => {
				uni.navigateTo({
					url: '/pages/order/order-detail?id=' + res.id
				})
			});
		}
	},
	computed: {
		// 获取当前时间段的索引
		currentTimeSegmentIndex() {
			if(!this.allPriceList.length) return -1;
			const currentMinutes = this.getCurrentMinutes();
			
			return this.allPriceList.findIndex(segment => {
				const processedData = this.processPriceData(segment);
				return currentMinutes >= processedData.timeRange.start && 
					   currentMinutes <= processedData.timeRange.end;
			});
		},
		isFormValid() {
			return this.formData.terminalId && 
				   this.formData.gunCode && 
				   this.formData.chargingDuration !== undefined;
		}
	}
}
</script>

<style scoped lang="scss">
	.page {
		padding: 20rpx;
		padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
	}
	
	
	.station-info {
		background: #fff;
		padding: 30rpx;
		border-radius: 28rpx;
		
		.title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
			font-family: "PINGFANG";
			margin-bottom: 30rpx;
		}
		
		.charger-list {
			.charger-item {
				position: relative;
				
				&:not(:last-child) {
					border-bottom: 1rpx solid #EEEEEE;
					margin-bottom: 20rpx;
					padding: 20rpx 0;
				}
				
				&:last-child {
					padding-top: 20rpx;
				}
				
				.status {
					width: 90rpx;
					flex-direction: column;
					align-items: center;
					margin-right: 30rpx;
					align-self: flex-start;
					
					.circle-progress {
						width: 90rpx;
						height: 90rpx;
						position: relative;
						margin-bottom: 15rpx;
					}
				}
				
				.info {
					overflow: hidden;
					margin-left: 30rpx;
					
					.name {
						font-size: 24rpx;
						color: #333;
						font-family: "PINGFANG";
						margin-bottom: 5rpx;
						font-weight: 400;
					}
					
					.sn, .power, .voltage, .standard {
						font-size: 22rpx;
						color: #777;
						font-family: "PINGFANG";
						margin-bottom: 5rpx;
					}
				}
				
				.super, .fast, .slow {
					position: absolute;
					right: 0;
					top: 20rpx;
					font-family: "PINGFANG";
					font-size: 20rpx;
					color: #fff;
					width: 32rpx;
					height: 32rpx;
					border-radius: 4rpx;
					justify-content: center;
				}
				
				.super {
					background: linear-gradient(to bottom, #947DFE, #6C4EFB);
				}
				
				.fast {
					background: linear-gradient(to bottom, #FF8924, #FF6800);
				}
				
				.slow {
					background: linear-gradient(to bottom, #42E0A2, #2CD291);
				}
			}
		}
	}
	
	.price-info {
		margin: 20rpx 0 0 0;
		background: #fff;
		padding: 30rpx;
		border-radius: 28rpx;
		
		.title {
			justify-content: space-between;
			margin-bottom: 30rpx;
			
			text {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				font-family: "PINGFANG";
			}
			
			.more {
				text {
					font-size: 24rpx;
					font-weight: 400;
					color: #999;
					margin-right: 10rpx;
				}
			}
		}
		
		.price-list {
			display: flex;
			gap: 20rpx;
			
			.price-item {
				border-radius: 10rpx;
				height: 126rpx;
				background: #F6FAFF url(~@/static/home/detail/price-box.png) no-repeat;
				background-size: auto 100%;
				position: relative;
				align-items: center;
				width: 100%;
				padding: 0 30rpx;
				
				.label {
					font-weight: 400;
					font-size: 24rpx;
					color: #777;
					flex: 1;
				}
				
				.time {
					flex: 1;
					font-size: 17rpx;
					color: #fff;
					font-weight: 400;
					font-family: "PINGFANG";
					width: 100%;
					position: absolute;
					left: 10rpx;
					top: 2rpx;
				}
				
				.price {
					align-items: baseline;
					justify-content: center;
					.symbol {
						font-size: 32rpx;
						color: #FC0A01;
						font-family: "PINGFANG";
						font-weight: 400;
					}
					
					.value {
						font-size: 44rpx;
						color: #FC0A01;
						font-family: "PINGFANG";
						font-weight: 600;
						margin: 0 5rpx;
					}
					
					.unit {
						font-size: 24rpx;
						color: #333;
						font-family: "PINGFANG";
					}
				}
			}
		}
	}
	
	.lightning {
		width: 16rpx;
		height: 22rpx;
	}

	.coupon-info {
		margin: 20rpx 0;
		background: #fff;
		padding: 30rpx;
		border-radius: 28rpx;
		
		.title {
			justify-content: space-between;
			
			text {
				&:first-child {
					font-family: "PINGFANG";
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
				}
				
				&:last-child {
					font-family: "PINGFANG";
					font-size: 24rpx;
					color: #777;
				}
			}
			
			.more {
				.label {
					font-size: 24rpx;
					color: #777;
					font-weight: 400;
					font-family: "PINGFANG";
				}
			}
		}
	}

	.charge-info, .payment-section, .duration-section {
		margin: 20rpx 0;
		background: #fff;
		padding: 30rpx 30rpx 10rpx 30rpx;
		border-radius: 28rpx;
	}

	.charge-title {
		font-family: "PINGFANG";
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.status {
		color: #FF3B30;
		font-size: 28rpx;
	}
	
	.add-plate {
		margin: 10rpx 0;
	}

	.add-btn {
		background: #3478F6;
		color: #fff;
		font-size: 22rpx;
		padding: 0rpx 30rpx;
		border-radius: 30rpx;
		border: none;
		font-family: "PINGFANG";
		
		&::after {
			border: none;
		}
	}

	.payment-option {
		align-items: center;
		margin-bottom: 20rpx;
		
		.item {
			width: 100%;
			height: 80rpx;
			border: 1rpx solid #f1f1f1;
			padding: 0 20rpx;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			&.active {
				background: rgba(7, 193, 96, 0.1);
				border-color: rgba(7, 193, 96, 0.3);
			}
			
			&.grey {
				background: #eee;
			}
			
			.text {
				font-size: 28rpx;
				font-weight: 400;
				font-family: "PINGFANG";
				margin-left: 20rpx;
			}
		}
	}

	.duration-options {
		.duration-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			// gap: 20rpx;
			
			.duration-item {
				text-align: center;
				padding: 15rpx 20rpx;
				background: #F5F5F5;
				border-radius: 100rpx;
				font-size: 28rpx;
				font-weight: 400;
				font-family: "PINGFANG";
				margin-bottom: 20rpx;
				
				&:nth-child(3n + 2) {
					margin-left: 20rpx;
					margin-right: 20rpx;
				}
				
				&.active {
					background: #ECF3FF;
					color: #3478F6;
				}
			}
		}
	}

	.start-charge-btn {
		background: #42E0A2;
		color: #fff;
		text-align: center;
		padding: 20rpx 30rpx;
		border-radius: 50rpx;
		font-size: 28rpx;
		font-weight: 400;
		font-family: "PINGFANG";
		margin-top: 60rpx;

		&.disabled {
			background: #ccc;
			opacity: 0.7;
			pointer-events: none;
		}
	}
	
	/* +++ 新增优惠券区域样式 +++ */
	  .coupon-section {
	    margin: 20rpx 0;
	    background: #fff;
	    padding: 30rpx;
	    border-radius: 28rpx;
	    
	    .coupon-select {
	      padding: 20rpx 0;
	      
	      .coupon-text {
	        font-size: 28rpx;
	        color: #333;
	        
	        &:active {
	          color: #42E0A2;
	        }
	      }
	    }
	  }
</style>